﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Remote;
using System.Net;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Xml;
using System.Data.SqlClient;
namespace NaviRankChecker
{
    public partial class appMain : Form
    {
        ChromeDriver chromeDriver;
        ChromeOptions chromeOptions;
        private Boolean drag;
        private int mousex;
        private int mousey;
        private Boolean blogFound = false;
        private Boolean cafeFound = false;
        private Boolean kinFound = false;
        private Boolean moFound = false;
        private int currentPage = 0;
        private String SEARCH_MODE = "";
        private String PC_URL = "";
        private Boolean PC_DONE = false;
        private Boolean MO_DONE = false;
        private static String DRIVER_PATH = AppDomain.CurrentDomain.BaseDirectory;
        private static String XML_PATH = AppDomain.CurrentDomain.BaseDirectory + "/SearchHistory.xml";
        private String M_URL = "";


        const int AW_SLIDE = 0X40000;
        const int AW_HOR_POSITIVE = 0X1;
        const int AW_HOR_NEGATIVE = 0X2;
        const int AW_BLEND = 0X80000;

        [DllImport("user32")]
        static extern bool AnimateWindow(IntPtr hwnd, int time, int flags);

        #region timer variables
        private int delay = 0;
        private int pause = 0;
        private int searchLink = 0;
        private int mobileSearch = 0;
        private int searchMo = 0;
        #endregion


        public appMain()
        {
            InitializeComponent();
           
        }
        private NaviRankChecker.rankHistory _rankH;
        public appMain(NaviRankChecker.rankHistory rankHistory)
        {
            // TODO: Complete member initialization
            InitializeComponent();
            this.rankHistory = rankHistory;
            _rankH = rankHistory;
        }

  

        #region function/methods

        private void resetAllTimers()
        {
            this.delay = 0;
            this.pause = 0;
            this.searchLink = 0;
            this.mobileSearch = 0;
            this.searchMo = 0;
        }

        private void resetTimerControl(Boolean bol)
        {
            this.delayTimer.Enabled = bol;
            this.pauseUrlType.Enabled = bol;
            this.searchLinkTimer.Enabled = bol;
            this.delayTimerMobile.Enabled = bol;
            this.searchMobileTimer.Enabled = bol;

        }


        public void initializeChrome()
        {

            chromeOptions = new ChromeOptions();
            chromeOptions.AddArguments("-incognito");
            DesiredCapabilities capabilities = DesiredCapabilities.Chrome();
            capabilities.SetCapability(ChromeOptions.Capability, chromeOptions);
            capabilities.SetCapability("resolution", "600x350");
            chromeDriver = new ChromeDriver(DRIVER_PATH, chromeOptions);

            if (txtURL.Text != null)
            {
                if (txtURL.Text.Contains("http://m."))
                {
                    this.SEARCH_MODE = "MOBILE";
                    chromeDriver.Navigate().GoToUrl("http://m.naver.com");
                    delayTimerMobile.Enabled = true;
                }
                else if (txtURL.Text.Contains("http://"))
                {
                    this.SEARCH_MODE = "PC";
                    chromeDriver.Navigate().GoToUrl("http://naver.com");
                    delayTimer.Enabled = true;
                }
            }
            //delay timer
            this.procPan.Visible = true;


        }

        private void startButton()
        {
            cmdStart.Tag = "start";
            cmdStart.Image = NaviRankChecker.Properties.Resources.start;
        }

        private void stopButton()
        {
            cmdStart.Tag = "stop";
            cmdStart.Image = NaviRankChecker.Properties.Resources.stop;
        }

        private String getInnerHtml(IWebElement element)
        {
            var remoteWebDriver = (RemoteWebElement)element;
            var javaScriptExecutor = (IJavaScriptExecutor)remoteWebDriver.WrappedDriver;
            var innerHtml = javaScriptExecutor.ExecuteScript("return arguments[0].innerHTML;", element).ToString();

            return innerHtml;
        }

        private String checkURL()
        {
            String urlType = "";
            if (txtURL.Text != null)
            {
                if (txtURL.Text.Contains("http://m.cafe.naver.com") || txtURL.Text.Contains("http://cafe.naver.com") || txtURL.Text.Contains("http://cafe.naver.com"))
                {
                    urlType = "CAFE";
                }
                else if (txtURL.Text.Contains("http://m.blog.naver.com") || txtURL.Text.Contains("http://blog.naver.com"))
                {
                    urlType = "BLOG";
                }
                else if (txtURL.Text.Contains("http://m.kin.naver.com") || txtURL.Text.Contains("http://kin.naver.com"))
                {
                    urlType = "KIN";
                }
            }


            return urlType;
        }

        private void clearData()
        {
            foreach (Control ctrl in this.resultsPan.Controls)
            {
                if (ctrl.GetType() == typeof(TextBox))
                {
                    ctrl.Text = null;
                }
            }


        }

        private void resetVariables()
        {
            this.SEARCH_MODE = "";
            this.PC_DONE = false;
            this.MO_DONE = false;
            this.currentPage = 0;
            this.blogFound = false;
            this.cafeFound = false;
            this.kinFound = false;
            this.moFound = false;
            this.PC_URL = "";
            this.M_URL = "";

        }
        #endregion

        #region timer events
        private void searchLinkTimer_Tick(object sender, EventArgs e)
        {
            //Console.WriteLine("searchLink: " + searchLink);
            if (searchLink == 2)
            {
                searchURL();

            }
            else
            {
                searchLink += 1;
            }
        }

        private IList<IWebElement> menuCollection(IWebElement doc, String xPath)
        {
            return doc.FindElements(By.XPath(xPath));
        }

        private void pauseUrlType_Tick(object sender, EventArgs e)
        {
            //Console.WriteLine(pause);
            if (pause == 2)
            {
                pause = 0;

                chromeDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

                //IWebElement pElem = chromeDriver.FindElement(By.XPath("//*"));
                //IList<IWebElement> elemColl = pElem.FindElements(By.XPath("//div[@class='lnb_menu']/ul/li/a/span"));

                Boolean exitLoop = false;
                foreach (IWebElement item in menuCollection(document("//*"), "//div[@class='lnb_menu']/ul/li/a/span"))
                {
                    try
                    {
                        switch (checkURL())
                        {
                            case "CAFE":

                                if (item.Text != null)
                                {
                                    if (item.Text.Equals("카페"))
                                    {
                                        item.Click();
                                        exitLoop = true;
                                    }
                                }
                                searchLinkTimer.Enabled = true;
                                break;
                            case "BLOG":

                                if (item.Text != null)
                                {
                                    if (item.Text.Equals("블로그"))
                                    {
                                        item.Click();
                                        exitLoop = true;
                                    }
                                }

                                searchLinkTimer.Enabled = true;
                                break;
                            case "KIN":
                                if (item.Text != null)
                                {
                                    if (item.Text.Equals("지식iN"))
                                    {
                                        item.Click();
                                        exitLoop = true;
                                    }
                                }
                                searchLinkTimer.Enabled = true;
                                break;
                            default:
                                break;
                        }
                    }
                    catch (Exception)
                    {


                    }
                    if (exitLoop)
                    {
                        break;
                    }

                }
                pauseUrlType.Enabled = false;
            }
            else
            {
                pause += 1;
            }

        }
        private void delayTimer_Tick(object sender, EventArgs e)
        {

            //Console.WriteLine(delay);
            if (delay == 2)
            {

                try
                {
                    //search keyword
                    IWebElement input = chromeDriver.FindElementById("query");
                    input.SendKeys(txtKey.Text);
                    input.Submit();
                    pauseUrlType.Enabled = true;
                    //get html elements


                    //reset delay and stop timer
                    // chromeDriver.Quit();
                    delay = 0;
                    delayTimer.Enabled = false;
                }
                catch (Exception)
                {


                }

            }
            else
            {
                delay += 1;
            }

        }
        #endregion

        #region  Move UI Events

        private Boolean isEmpty()
        {
            Boolean xResult = false;

            foreach (Control ctrl in mainPan.Controls)
            {
                if (ctrl.GetType() == typeof(TextBox))
                {
                    if (ctrl.Text == null || ctrl.Text == "")
                    {
                        if (String.Equals(ctrl.Tag.ToString(), "key"))
                        {
                            epEmptyFields.SetError(ctrl, "Fields cannot be empty!");
                        }
                        else if (String.Equals(ctrl.Tag.ToString(), "url"))
                        {
                            epEmptyFields.SetError(ctrl, "Fields cannot be empty!");
                        }

                        xResult = true;
                    }
                    else
                    {
                        if (String.Equals(ctrl.Tag.ToString(), "key"))
                        {
                            epEmptyFields.Dispose();
                        }
                        else if (String.Equals(ctrl.Tag.ToString(), "url"))
                        {
                            epEmptyFields.Dispose();
                        }
                        else
                        {
                            epEmptyFields.Dispose();
                        }
                    }
                }
                else if (ctrl.GetType() == typeof(ComboBox))
                {
                    if (ctrl.Text == null || ctrl.Text == "")
                    {
                        epEmptyFields.SetError(ctrl, "Fields cannot be empty!");
                        xResult = true;
                    }
                    else
                    {
                        epEmptyFields.Dispose();
                    }
                }
            }

            return xResult;
        }

        private void cmdStart_Click(object sender, EventArgs e)
        {
            if (!isEmpty())
            {
                if (String.Equals("start", cmdStart.Tag.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {

                    createXMLFile();

                    epEmptyFields.Dispose();
                    stopButton();
                    clearData();
                    initializeChrome();
                }
                else if (String.Equals("stop", cmdStart.Tag.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {
                    clearData();
                    resetAllTimers();
                    resetTimerControl(false);
                    procPan.Visible = false;
                    chromeDriver.Quit();
                    startButton();
                }
                else
                {
                }
            }
            else
            {

            }

            Properties.Settings set = new Properties.Settings();
            set.lastKeyword = txtKey.Text;
            set.lastUrl = txtURL.Text;
            set.Save();

        }

        private void cmdCLose_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void cmdMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void topPan_MouseDown(object sender, MouseEventArgs e)
        {
            this.drag = true;
            mousex = System.Windows.Forms.Cursor.Position.X - this.Left;
            mousey = System.Windows.Forms.Cursor.Position.Y - this.Top;
        }

        private void topPan_MouseMove(object sender, MouseEventArgs e)
        {
            if (drag)
            {
                this.Top = System.Windows.Forms.Cursor.Position.Y - mousey;
                this.Left = System.Windows.Forms.Cursor.Position.X - mousex;
                rh = new rankHistory();
                rh.Location = new Point(this.Left + this.Width, this.Top);
                //rh.Location = new Point(this.Location.X, this.Location.Y);
            }
        }

        private void topPan_MouseUp(object sender, MouseEventArgs e)
        {
            this.drag = false;
        }

        private void pbNav_MouseDown(object sender, MouseEventArgs e)
        {
            this.drag = true;
            mousex = System.Windows.Forms.Cursor.Position.X - this.Left;
            mousey = System.Windows.Forms.Cursor.Position.Y - this.Top;
        }

        private void pbNav_MouseMove(object sender, MouseEventArgs e)
        {
            if (drag)
            {
                this.Top = System.Windows.Forms.Cursor.Position.Y - mousey;
                this.Left = System.Windows.Forms.Cursor.Position.X - mousex;
            }
        }

        private void pbNav_MouseUp(object sender, MouseEventArgs e)
        {
            this.drag = false;
        }

        private void lblVersion_MouseDown(object sender, MouseEventArgs e)
        {
            this.drag = true;
            mousex = System.Windows.Forms.Cursor.Position.X - this.Left;
            mousey = System.Windows.Forms.Cursor.Position.Y - this.Top;
        }

        private void lblVersion_MouseMove(object sender, MouseEventArgs e)
        {
            if (drag)
            {
                this.Top = System.Windows.Forms.Cursor.Position.Y - mousey;
                this.Left = System.Windows.Forms.Cursor.Position.X - mousex;
            }
        }

        private void lblVersion_MouseUp(object sender, MouseEventArgs e)
        {
            this.drag = false;
        }

        private void cmdCLose_MouseHover(object sender, EventArgs e)
        {
            this.cmdCLose.Image = Properties.Resources.closeHover;
        }

        private void cmdMin_MouseHover(object sender, EventArgs e)
        {
            this.cmdMin.Image = Properties.Resources.min_hover;
        }

        private void cmdMin_MouseLeave(object sender, EventArgs e)
        {
            this.cmdMin.Image = Properties.Resources.min;
        }

        private void cmdCLose_MouseLeave(object sender, EventArgs e)
        {
            this.cmdCLose.Image = Properties.Resources.close;
        }

        private void delayTimerMobile_Tick(object sender, EventArgs e)
        {
            if (mobileSearch == 2)
            {
                try
                {
                    IWebElement input = chromeDriver.FindElementById("query");
                    input.SendKeys(txtKey.Text);
                    input.Submit();
                    searchLinkTimer.Enabled = true;
                    delayTimerMobile.Enabled = false;
                    searchLink = 0;
                    mobileSearch = 0;
                }
                catch (Exception)
                {


                }

            }
            else
            {
                mobileSearch += 1;
            }
        }

        private string getExternalIp()
        {
            try
            {
                string externalIP;
                externalIP = (new WebClient()).DownloadString("http://www.ipip.kr");
                externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                             .Matches(externalIP)[0].ToString();
                return externalIP;
            }
            catch { return null; }
        }

        private void searchMobileTimer_Tick(object sender, EventArgs e)
        {
            if (searchMo == 10)
            {


            }
            else
            {
                searchMo += 1;
            }

        }

        private void cmdStart_MouseHover(object sender, EventArgs e)
        {
            if (String.Equals("start", cmdStart.Tag.ToString(), StringComparison.CurrentCultureIgnoreCase))
            {
                cmdStart.Image = Properties.Resources.start_hover;
            }
            else
            {
                cmdStart.Image = Properties.Resources.stop_hover;
            }

        }

        private void cmdStart_MouseLeave(object sender, EventArgs e)
        {
            if (String.Equals("start", cmdStart.Tag.ToString(), StringComparison.CurrentCultureIgnoreCase))
            {
                cmdStart.Image = Properties.Resources.start;
            }
            else
            {
                cmdStart.Image = Properties.Resources.stop;
            }
        }

        #endregion



        #region Main Navi Functions

        private IWebElement document(String xPath)
        {
            return chromeDriver.FindElement(By.XPath(xPath));
        }

        private IList<IWebElement> docList(IWebElement doc, String xPath)
        {
            return doc.FindElements(By.XPath(xPath));
        }

        private int getCurrentPage(IWebElement doc, String xPath)
        {
            int _page = 0;

            foreach (IWebElement item in doc.FindElements(By.XPath(xPath)))
            {
                _page = Convert.ToInt32(item.Text);
                break;
            }

            return _page;
        }

        private IList<IWebElement> pageList(IWebElement doc, String xPath)
        {
            return doc.FindElements(By.XPath(xPath));
        }

        private IList<IWebElement> goToNextPage(IWebElement doc, String xPath)
        {
            return doc.FindElements(By.XPath(xPath));
        }

        private void searchURL()
        {


            int _pageLimit = Convert.ToInt32(cmbPageLmit.Text);



            if (txtURL.Text.Contains("http://m."))
            {


                if (txtURL.Text.Contains("kin"))
                {
                    PC_URL = PC_URL.Replace("/mobile", "");
                }
                PC_URL = txtURL.Text.Replace("http://m.", "http://");
            }
            else
            {
                PC_URL = txtURL.Text;
            }


            if (SEARCH_MODE == "PC" && !PC_DONE)
            {
                switch (checkURL())
                {

                    case "BLOG":
                        try
                        {
                            chromeDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
                            IWebElement docAll = chromeDriver.FindElement(By.XPath("//*"));
                            IList<IWebElement> curPage = docAll.FindElements(By.XPath("//div[@class='paging']/strong"));


                            this.currentPage = getCurrentPage(document("//*"), "//div[@class='paging']/strong");
                            this.lblPage.Text = currentPage + "";


                            //IList<IWebElement> getRank = docAll.FindElements(By.XPath("//div[@class='blog section _blogBase']/ul/li/dl/dt/a"));
                            foreach (IWebElement item in docList(document("//*"), "//div[@class='blog section _blogBase']/ul/li/dl/dt/a"))
                            {

                                if (item.GetAttribute("onclick") != null)
                                {
                                    //richTextBox1.AppendText(item.GetAttribute("onclick"));
                                    if (item.GetAttribute("href") != null)
                                    {
                                        //Console.WriteLine(item.GetAttribute("href").Replace("?Redirect=Log&logNo=", "/"));
                                        if (item.GetAttribute("href").Replace("?Redirect=Log&logNo=", "/").Equals(PC_URL))
                                        {

                                            String rank = item.GetAttribute("onclick");
                                            //Console.WriteLine(rank);
                                            String[] separator = new String[] { "*i.tit&r=" };
                                            String[] rankArr = rank.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                                            rank = rankArr[1];
                                            char[] rankChar = rank.ToCharArray();

                                            if (char.IsNumber(rankChar[2]))
                                            {
                                                rank = rankChar[0].ToString() + rankChar[1].ToString() + rankChar[1].ToString();
                                            }
                                            else if (char.IsNumber(rankChar[1]))
                                            {
                                                rank = rankChar[0].ToString() + rankChar[1].ToString();
                                            }
                                            else
                                            {
                                                rank = rankChar[0].ToString();
                                            }

                                            txtPCRank.Text = rank;
                                            txtPCPage.Text = this.currentPage.ToString();
                                            this.blogFound = true;
                                            this.SEARCH_MODE = "MOBILE";
                                            PC_DONE = true;
                                        }

                                    }


                                }
                            }


                            if (!blogFound)
                            {
                                currentPage += 1;

                                foreach (IWebElement pg in goToNextPage(document("//*"), "//div[@class='paging']/a"))
                                {
                                    int docPage;
                                    if (pg.Text != null)
                                    {
                                        bool isNum = int.TryParse(pg.Text, out docPage);
                                        if (isNum)
                                        {
                                            if (docPage <= _pageLimit)
                                            {
                                                if (pg.Text == currentPage.ToString())
                                                {
                                                    pg.Click();
                                                    searchLink = 0;
                                                    searchLinkTimer.Enabled = true;
                                                    break;
                                                }
                                            }
                                            else
                                            {

                                                txtPCPage.Text = "NF";
                                                txtPCRank.Text = "NF";
                                                pauseUrlType.Enabled = false;
                                                delayTimer.Enabled = false;
                                                searchLink = 0;
                                                searchLinkTimer.Enabled = false;
                                                procPan.Visible = true;
                                                lblPage.Text = "0";

                                                pauseUrlType.Enabled = false;
                                                delayTimer.Enabled = false;
                                                searchLink = 0;
                                                searchLinkTimer.Enabled = false;
                                                procPan.Visible = true;
                                                lblPage.Text = "0";
                                                //chromeDriver.Quit();
                                                if (!MO_DONE)
                                                {
                                                    SEARCH_MODE = "MOBILE";
                                                    PC_DONE = true;
                                                    currentPage = 0;
                                                    mobileSearch = 0;
                                                    chromeDriver.Navigate().GoToUrl("http://m.naver.com");
                                                    delayTimerMobile.Enabled = true;
                                                }
                                                else
                                                {
                                                    this.procPan.Visible = false;
                                                    resetVariables();
                                                    resetAllTimers();
                                                    resetTimerControl(false);
                                                    chromeDriver.Quit();
                                                    startButton();
                                                }
                                                break;

                                            }
                                        }





                                    }
                                }
                            }
                            else
                            {
                                pauseUrlType.Enabled = false;
                                delayTimer.Enabled = false;
                                searchLink = 0;
                                searchLinkTimer.Enabled = false;
                                procPan.Visible = true;
                                lblPage.Text = "0";
                                //chromeDriver.Quit();
                                if (!MO_DONE)
                                {
                                    SEARCH_MODE = "MOBILE";
                                    currentPage = 0;
                                    mobileSearch = 0;
                                    chromeDriver.Navigate().GoToUrl("http://m.naver.com");
                                    delayTimerMobile.Enabled = true;
                                }
                                else
                                {
                                    this.procPan.Visible = false;
                                    resetVariables();
                                    resetAllTimers();
                                    resetTimerControl(false);
                                    chromeDriver.Quit();
                                    startButton();
                                }

                            }


                        }
                        catch (Exception ex)
                        {

                            Console.WriteLine(ex.ToString());
                        }

                        break;
                    case "CAFE":
                        chromeDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

                        //get current page  cafe_article section _cafeBase
                        currentPage = getCurrentPage(document("//*"), "//div[@class='paging']/strong");
                        lblPage.Text = currentPage + "";
                        //Console.WriteLine("Cafe Current page : " + currentPage);

                        foreach (IWebElement r in docList(document("//*"), "//div[@class='cafe_article section _cafeBase']/ul/li/dl/dt/a"))
                        {
                            if (r.GetAttribute("onclick") != null)
                            {
                                if (r.GetAttribute("href") != null)
                                {
                                    //Console.WriteLine(r.GetAttribute("href"));
                                    if (r.GetAttribute("href").Equals(PC_URL))
                                    {
                                        cafeFound = true;

                                        String rank = r.GetAttribute("onclick");
                                        //Console.WriteLine(rank);
                                        String[] separator = new String[] { "*a.tit&r=" };
                                        String[] rankArr = rank.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                                        rank = rankArr[1];
                                        char[] rankChar = rank.ToCharArray();

                                        if (char.IsNumber(rankChar[2]))
                                        {
                                            rank = rankChar[0].ToString() + rankChar[1].ToString() + rankChar[1].ToString();
                                        }
                                        else if (char.IsNumber(rankChar[1]))
                                        {
                                            rank = rankChar[0].ToString() + rankChar[1].ToString();
                                        }
                                        else
                                        {
                                            rank = rankChar[0].ToString();
                                        }
                                        this.SEARCH_MODE = "MOBILE";
                                        this.PC_DONE = true;
                                        txtPCRank.Text = rank;
                                        txtPCPage.Text = this.currentPage.ToString();
                                        this.kinFound = true;
                                        break;
                                    }
                                }
                            }

                        }


                        //if not found then go to next page
                        if (!cafeFound)
                        {
                            currentPage += 1;
                            foreach (IWebElement pg in goToNextPage(document("//*"), "//div[@class='paging']/a"))
                            {

                                int docPage;
                                try
                                {
                                    bool isNum = int.TryParse(pg.Text, out docPage);

                                    if (isNum)
                                    {
                                        //Console.WriteLine("Document Page : " + docPage + ":::::::Current Page" + _pageLimit);
                                        if (docPage <= _pageLimit)
                                        {
                                            if (docPage == currentPage)
                                            {
                                                pg.Click();
                                                searchLink = 0;
                                                searchLinkTimer.Enabled = true;
                                                break;

                                            }
                                        }
                                        else
                                        {
                                            txtPCPage.Text = "NF";
                                            txtPCRank.Text = "NF";
                                            pauseUrlType.Enabled = false;
                                            delayTimer.Enabled = false;
                                            searchLink = 0;
                                            searchLinkTimer.Enabled = false;
                                            procPan.Visible = true;
                                            lblPage.Text = "0";

                                            pauseUrlType.Enabled = false;
                                            delayTimer.Enabled = false;
                                            searchLink = 0;
                                            searchLinkTimer.Enabled = false;
                                            procPan.Visible = true;
                                            lblPage.Text = "0";
                                            //chromeDriver.Quit();
                                            if (!MO_DONE)
                                            {
                                                PC_DONE = true;
                                                SEARCH_MODE = "MOBILE";
                                                currentPage = 0;
                                                mobileSearch = 0;
                                                chromeDriver.Navigate().GoToUrl("http://m.naver.com");
                                                delayTimerMobile.Enabled = true;
                                            }
                                            else
                                            {
                                                this.procPan.Visible = false;
                                                resetVariables();
                                                resetAllTimers();
                                                resetTimerControl(false);
                                                chromeDriver.Quit();
                                                startButton();
                                            }
                                            break;
                                        }
                                    }
                                }
                                catch (Exception)
                                {


                                }



                            }
                        }
                        else
                        {
                            pauseUrlType.Enabled = false;
                            delayTimer.Enabled = false;
                            searchLink = 0;
                            searchLinkTimer.Enabled = false;
                            procPan.Visible = true;
                            lblPage.Text = "0";
                            //chromeDriver.Quit();
                            if (!MO_DONE)
                            {

                                PC_DONE = true;
                                SEARCH_MODE = "MOBILE";
                                currentPage = 0;
                                mobileSearch = 0;
                                chromeDriver.Navigate().GoToUrl("http://m.naver.com");
                                delayTimerMobile.Enabled = true;
                            }
                            else
                            {
                                this.procPan.Visible = false;
                                resetVariables();
                                resetAllTimers();
                                resetTimerControl(false);
                                chromeDriver.Quit();
                                startButton();
                            }
                        }


                        break;
                    case "KIN":
                        String[] kinSeparator = new String[] { "&qb=" };
                        String[] kinURL = PC_URL.Split(kinSeparator, StringSplitOptions.RemoveEmptyEntries);
                        //kinURL[0];
                        try
                        {

                            chromeDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
                            //  IWebElement docAll = chromeDriver.FindElement(By.XPath("//*"));

                            // IList<IWebElement> compareURL = docAll.FindElements(By.XPath("//div[@class='blog section _blogBase']/ul/li/dl/dd/span/a"));
                            // IList<IWebElement> curPage = docAll.FindElements(By.XPath("//div[@class='paging']/strong"));
                            //Get Page
                            //foreach (IWebElement p in curPage)
                            //{
                            this.currentPage = getCurrentPage(document("//*"), "//div[@class='paging']/strong");
                            this.lblPage.Text = currentPage + 1 + "";
                            //Console.WriteLine("Current Page : " + this.currentPage);
                            // break;
                            //}//main loop
                            // IList<IWebElement> getRank = docAll.FindElements(By.XPath("//div[@class='kinn section _kinBase']/ul/li/dl/dt/a"));
                            //
                            Boolean exitRankLoop = false;
                            foreach (IWebElement item in docList(document("//*"), "//div[@class='kinn section _kinBase']/ul/li/dl/dt/a"))
                            {
                                if (item.GetAttribute("href") != null)
                                {
                                    if (item.GetAttribute("href").Contains(kinURL[0].ToString().Replace("mobile/", "")))
                                    {
                                        if (item.GetAttribute("onclick") != null)
                                        {
                                            String rank = item.GetAttribute("onclick");
                                            //Console.WriteLine(rank);
                                            String[] separator = new String[] { "*q.tit&r=" };
                                            String[] rankArr = rank.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                                            rank = rankArr[1];
                                            char[] rankChar = rank.ToCharArray();

                                            if (char.IsNumber(rankChar[2]))
                                            {
                                                rank = rankChar[0].ToString() + rankChar[1].ToString() + rankChar[1].ToString();
                                            }
                                            else if (char.IsNumber(rankChar[1]))
                                            {
                                                rank = rankChar[0].ToString() + rankChar[1].ToString();
                                            }
                                            else
                                            {
                                                rank = rankChar[0].ToString();
                                            }
                                            this.SEARCH_MODE = "MOBILE";
                                            this.PC_DONE = true;
                                            txtPCRank.Text = rank;
                                            txtPCPage.Text = this.currentPage.ToString();
                                            this.kinFound = true;
                                            exitRankLoop = true;

                                        }//on click null if
                                    }//contains if
                                }//fref null if
                                if (exitRankLoop)
                                {
                                    break;
                                }
                            }//parent loop

                            if (!kinFound)
                            {
                                currentPage += 1;
                                //  IList<IWebElement> page = docAll.FindElements(By.XPath("//div[@class='paging']/a"));
                                foreach (IWebElement pg in goToNextPage(document("//*"), "//div[@class='paging']/a"))
                                {
                                    int docPage;

                                    try
                                    {
                                        bool isNum = int.TryParse(pg.Text, out docPage);
                                        if (isNum)
                                        {
                                            if (pg.Text != null)
                                            {
                                                if (Convert.ToInt32(pg.Text) <= _pageLimit)
                                                {
                                                    if (pg.Text == currentPage.ToString())
                                                    {
                                                        pg.Click();
                                                        searchLink = 0;
                                                        searchLinkTimer.Enabled = true;
                                                        break;
                                                    }
                                                }
                                                else
                                                {

                                                    txtPCPage.Text = "NF";
                                                    txtPCRank.Text = "NF";
                                                    pauseUrlType.Enabled = false;
                                                    delayTimer.Enabled = false;
                                                    searchLink = 0;
                                                    searchLinkTimer.Enabled = false;
                                                    procPan.Visible = true;
                                                    lblPage.Text = "0";
                                                    if (!MO_DONE)
                                                    {
                                                        PC_DONE = true;
                                                        SEARCH_MODE = "MOBILE";
                                                        currentPage = 0;
                                                        mobileSearch = 0;
                                                        chromeDriver.Navigate().GoToUrl("http://m.naver.com");
                                                        delayTimerMobile.Enabled = true;
                                                    }
                                                    else
                                                    {
                                                        this.procPan.Visible = false;
                                                        resetVariables();
                                                        resetAllTimers();
                                                        resetTimerControl(false);
                                                        chromeDriver.Quit();
                                                        startButton();

                                                    }
                                                    break;
                                                }


                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {


                                    }


                                }
                            }
                            else
                            {
                                pauseUrlType.Enabled = false;
                                delayTimer.Enabled = false;
                                searchLink = 0;
                                searchLinkTimer.Enabled = false;
                                procPan.Visible = true;
                                lblPage.Text = "0";
                                if (!MO_DONE)
                                {

                                    PC_DONE = true;
                                    SEARCH_MODE = "MOBILE";
                          
                                    currentPage = 0;
                                    mobileSearch = 0;
                                    chromeDriver.Navigate().GoToUrl("http://m.naver.com");
                                    delayTimerMobile.Enabled = true;
                                }
                                else
                                {
                                    this.procPan.Visible = false;
                                    resetVariables();
                                    resetAllTimers();
                                    resetTimerControl(false);
                                    chromeDriver.Quit();
                                    startButton();

                                }
                            }
                        }
                        catch (Exception)
                        {


                        }


                        break;

                    default:
                        break;
                }//PC Switch END
                if (PC_DONE && MO_DONE)
                {
                    resetVariables();
                    resetAllTimers();
                    resetTimerControl(false);
                    chromeDriver.Quit();
                    startButton();
                }

            }
            else if (SEARCH_MODE == "MOBILE" && !MO_DONE)
            {
                try
                {

                    chromeDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
                    //IWebElement docAll = chromeDriver.FindElement(By.XPath("//*"));

                    // IList<IWebElement> compareURL = docAll.FindElements(By.XPath("//div[@class='blog section _blogBase']/ul/li/dl/dd/span/a"));
                    //IList<IWebElement> curPage = docAll.FindElements(By.XPath("//div[@class='api_bx paging_total']/span/a"));
                    //Get Page
                    foreach (IWebElement p in pageList(document("//*"), "//div[@class='api_bx paging_total']/span/a"))
                    {
                        if ((p.GetAttribute("class").Contains("spcm_bf pgn now")) || (p.GetAttribute("class").Contains(" spcm_bf pgn now")))
                        {
                            this.currentPage = Convert.ToInt32(p.Text);
                            this.lblPage.Text = currentPage + "";
                            //Console.WriteLine("Current Page : " + this.currentPage);
                            break;
                        }

                    }//main loop
                    if (txtURL.Text.Contains("http://m."))
                    {
                        this.M_URL = txtURL.Text;

                    }
                    else if (txtURL.Text.Contains("kin"))
                    {
                        String[] separator = new String[] { "/" };
                        String[] _urlKinArr = txtURL.Text.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                        this.M_URL = String.Format("{0}//{1}/mobile/{2}/{3}", _urlKinArr[0], _urlKinArr[1], _urlKinArr[2], _urlKinArr[3]);
                        String[] separator1 = new String[] { "&qb=" };
                        String[] newMUrl = M_URL.Split(separator1, StringSplitOptions.RemoveEmptyEntries);

                        this.M_URL = newMUrl[0].Replace("http://", "http://m.");

                    }
                    else
                    {
                        this.M_URL = txtURL.Text.Replace("http://", "http://m.");
                    }

                    //search URL//*[@id="ct"]
                    // IList<IWebElement> getRank = docAll.FindElements(By.XPath("//*[@id='ct']/section/ul/li/a"));
                    foreach (IWebElement item in docList(document("//*"), "//*[@id='ct']/section/ul/li/a"))
                    {
                        if (item.GetAttribute("href") != null)
                        {
                            //Console.WriteLine(item.GetAttribute("href"));
                            if (item.GetAttribute("href").Contains(M_URL))
                            {
                                if (item.GetAttribute("onclick") != null)
                                {
                                    String rank = item.GetAttribute("onclick");
                                    //Console.WriteLine(rank);
                                    String[] separator = new String[] { ".link&r=" };
                                    String[] rankArr = rank.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                                    rank = rankArr[1];
                                    char[] rankChar = rank.ToCharArray();

                                    if (char.IsNumber(rankChar[2]))
                                    {
                                        rank = rankChar[0].ToString() + rankChar[1].ToString() + rankChar[1].ToString();
                                    }
                                    else if (char.IsNumber(rankChar[1]))
                                    {
                                        rank = rankChar[0].ToString() + rankChar[1].ToString();
                                    }
                                    else
                                    {
                                        rank = rankChar[0].ToString();
                                    }
                                    this.SEARCH_MODE = "PC";
                                    this.MO_DONE = true;
                                    this.moFound = true;
                                    txtMRank.Text = rank;
                                    txtMPage.Text = this.currentPage.ToString();
                                    delayTimer.Enabled = true;

                                }
                            }
                        }
                    }
                    //next page

                    if (!moFound)
                    {
                        currentPage += 1;
                        //IList<IWebElement> page = docAll.FindElements(By.XPath("//div[@class='api_bx paging_total']/span/a"));
                        //Get Page
                        foreach (IWebElement p in goToNextPage(document("//*"), "//div[@class='api_bx paging_total']/span/a"))
                        {
                            if (p.Text != null)
                            {
                                if (_pageLimit > 15)
                                {
                                    _pageLimit =14;
                                }

                                if (Convert.ToInt32(p.Text) <= _pageLimit)
                                {

                                    if (Convert.ToInt32(p.Text) != 14)
                                    {
                                        if (Convert.ToInt32(p.Text) == currentPage)
                                        {


                                            p.Click();
                                            searchLink = 0;
                                            searchLinkTimer.Enabled = true;
                                            break;
                                        }
                                    }

                                    else
                                    {


                                        if (!PC_DONE)
                                        {

                                            MO_DONE = true;
                                            txtMPage.Text = "NF";
                                            txtMRank.Text = "NF";
                                            SEARCH_MODE = "PC";
                                            procPan.Visible = true;
                                            lblPage.Text = "0";
                                            chromeDriver.Navigate().GoToUrl("http://naver.com");
                                            searchLink = 0;
                                            delay = 0;
                                            pause = 0;
                                            delayTimerMobile.Enabled = false;
                                            searchLinkTimer.Enabled = false;
                                            pauseUrlType.Enabled = false;
                                            delayTimer.Enabled = true;
                                        }

                                        else
                                        {

                                            MO_DONE = true;
                                            txtMPage.Text = "NF";
                                            txtMRank.Text = "NF";
                                            this.procPan.Visible = false;
                                            resetVariables();
                                            resetAllTimers();
                                            resetTimerControl(false);
                                            chromeDriver.Quit();
                                            startButton();

                                            searchLink = 0;
                                            delay = 0;
                                            pause = 0;
                                            delayTimerMobile.Enabled = false;
                                            searchLinkTimer.Enabled = false;
                                            pauseUrlType.Enabled = false;
                                        }


                                    }


                                }
                                else
                                {
                                    MO_DONE = true;
                                    txtMPage.Text = "NF";
                                    txtMRank.Text = "NF";

                                    SEARCH_MODE = "PC";
                                    procPan.Visible = true;
                                    lblPage.Text = "0";
                                    chromeDriver.Navigate().GoToUrl("http://naver.com");
                                    searchLink = 0;
                                    delay = 0;
                                    pause = 0;
                                    delayTimerMobile.Enabled = false;
                                    searchLinkTimer.Enabled = false;
                                    pauseUrlType.Enabled = false;
                                    delayTimer.Enabled = true;


                                }
                            }
                            //break;
                        }//main loop
                    }
                    else
                    {
                        MO_DONE = true;
                        SEARCH_MODE = "PC";
                        procPan.Visible = true;
                        lblPage.Text = "0";
                        if (!PC_DONE)
                        {
                            chromeDriver.Navigate().GoToUrl("http://naver.com");
                            delayTimer.Enabled = true;
                        }
                        else
                        {
                            this.procPan.Visible = false;
                            resetVariables();
                            resetAllTimers();
                            resetTimerControl(false);
                            chromeDriver.Quit();
                            startButton();
                        }

                        searchLink = 0;
                        delay = 0;
                        pause = 0;
                        delayTimerMobile.Enabled = false;
                        searchLinkTimer.Enabled = false;
                        pauseUrlType.Enabled = false;

                    }
                }
                catch (Exception)
                {
                    // Console.WriteLine();

                }//end try mobile
                if (PC_DONE && MO_DONE)
                {
                    resetVariables();
                    resetAllTimers();
                    resetTimerControl(false);
                    chromeDriver.Quit();
                    startButton();
                }
            }
            else
            {
                if (PC_DONE && MO_DONE)
                {
                    resetVariables();
                    resetAllTimers();
                    resetTimerControl(false);
                    chromeDriver.Quit();
                    startButton();
                }

            }
        }
        #endregion

        private void appMain_Load(object sender, EventArgs e)
        {
            lblIP.Text = getExternalIp();
            lblIP.Visible = true;

            Properties.Settings set = new Properties.Settings();

            try
            {
                bgNewData.RunWorkerAsync();
                cmbPageLmit.SelectedIndex = 13;
                if (set.lastKeyword != null && set.lastUrl != null)
                {
                    txtKey.Text = set.lastKeyword;
                    txtURL.Text = set.lastUrl;
                }

            }
            catch (Exception)
            {


            }

        }

        rankHistory rh;

        private void llblHistory_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
          //  bool IsOpen = false;
            FormCollection fc = Application.OpenForms;
            foreach (Form f in fc)
            {

                if (f.Name == "rankHistory")
                {
                    if (!Globals.FormActivated)
                    {
                        //IsOpen = true;
                        f.Focus();
                        break;
                    }
                    else
                    {
                       // IsOpen = false;

                        break;
                    }


                }
            }

            if (!Globals.FormActivated)
            {
                Globals.FormActivated = true;
                rh = new rankHistory(this);
               
               // TestSelenium.rankHistory.passNewData rankH= new TestSelenium.rankHistory.passNewData(newData);
                rh.pnd = new NaviRankChecker.rankHistory.passNewData(newData);

                rh.Show();
                //Application.Run(new rankHistory());
            }
            else
            {
                foreach (Form f in Application.OpenForms)
                {
                    if (f.Name.Equals("rankHistory"))
                    {
                        f.Dispose();
                        break;
                    }
                }


                Globals.FormActivated = true;
                rh = new rankHistory(this);
                // TestSelenium.rankHistory.passNewData rankH= new TestSelenium.rankHistory.passNewData(newData);
                rh.pnd = new NaviRankChecker.rankHistory.passNewData(newData);
                rh.Show();

            }
        }

        private void refdgv()
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name.Equals("rankHistory"))
                {
                    f.Dispose();
                    break;
                }
            }


            Globals.FormActivated = true;
            rh = new rankHistory();
            // TestSelenium.rankHistory.passNewData rankH= new TestSelenium.rankHistory.passNewData(newData);
            rh.pnd = new NaviRankChecker.rankHistory.passNewData(newData);
            rh.Show();
        }

        private void newData(string newKey, string newUrl)
        {
            txtKey.Text = newKey;
            txtURL.Text = newUrl;
        }


        public delegate void newDataUpdate(Boolean nd);
        public newDataUpdate update;
        private rankHistory rankHistory;


        private void createXMLFile()
        {
            if (!System.IO.File.Exists(XML_PATH))
            {
                DataTable dt = new DataTable("History");
                dt.Columns.Add("Keyword", typeof(string));
                dt.Columns.Add("URL", typeof(string));
                dt.PrimaryKey = new DataColumn[] { dt.Columns["URL"] };
                dt.Rows.Add(txtKey.Text, txtURL.Text);
                DataSet ds = new DataSet("SearchHistory");
                ds.Tables.Add(dt);
                System.IO.StringWriter writer = new System.IO.StringWriter();
                ds.WriteXml(XML_PATH);
                ds.GetXml();
                refdgv();
                //this.refreshDGV();
            }
            else
            {
                DataTable dt = new DataTable();
                DataSet ds = new DataSet();
                ds.ReadXml(XML_PATH);
                dt = ds.Tables["History"];
                dt.PrimaryKey = new DataColumn[] { dt.Columns["URL"] };
                String _findUrl = txtURL.Text;
                DataRow findRow = dt.Rows.Find(_findUrl);
                if (findRow != null)
                {
                    //url found




                }
                else
                {

                    //add new URL
                    DataRow newURL = dt.NewRow();
                    newURL["Keyword"] = txtKey.Text;
                    newURL["URL"] = txtURL.Text;
                    dt.Rows.Add(newURL);
                    System.IO.StringWriter writer = new System.IO.StringWriter();
                    ds.WriteXml(XML_PATH);
                    //this.refreshDGV();
                    refdgv();
                    if (update!=null)
                    {
                        update(true);
                    }
                   
                }
            }
        }


        public delegate void DoEvent();
        public event DoEvent refreshDGV;
    
    }
   
  
}
